﻿#Region "Import Libraries"

Imports System.IO
Imports System.Text
Imports System.Security.Cryptography

#End Region

Public Class Rijndael 'AES Encrypt

    ' The key and initialization vector : change them for your application
    Private Shared _key() As Byte = {43, 126, 21, 22, 40, 82, 46, 90, 85, 9, 21, 120, 9, 49, 79, 60}
    Private Shared _iv() As Byte = {83, 71, 26, 58, 54, 35, 22, 11, 83, 71, 26, 58, 54, 35, 22, 11}

    ' returns the default size, in bits of the iv
    Public Function BlockSize() As Integer
        Dim aes As New RijndaelManaged()

        Return aes.BlockSize
    End Function

    ' returns the default size, in bits of the key
    Public Function KeySize() As Integer
        Dim aes As New RijndaelManaged()

        Return aes.KeySize
    End Function

    ' decrypts a string that was encrypted using the Encrypt method

    Public Shared Function Decrypt(ByVal data As String) As String
        If (data.StartsWith("<packet>")) Then
            data = data.Replace("<packet>", "")
            data = data.Replace("</packet>", "")
        End If

        ' Try
        Dim inBytes() As Byte = Convert.FromBase64String(data)
        Dim utf8 As New UTF8Encoding
        'Dim inBytes() As Byte = utf8.GetBytes(data) ' ascii encoding uses 7

        Dim mStream As New MemoryStream(inBytes, 0, inBytes.Length) ' instead of writing the decrypted text

        Dim aes As New RijndaelManaged()
        Dim cs As New CryptoStream(mStream, aes.CreateDecryptor(_key, _iv), CryptoStreamMode.Read)

        Dim sr As New StreamReader(cs)

        ' Return ("<packet>" + sr.ReadToEnd() + "</packet>") 'Pass the decrypted message to the application
        Return (sr.ReadToEnd())
        'Catch ex As Exception
        'Throw ex

        'End Try
    End Function


    ' Encrypts a given string
    Public Shared Function Encrypt(ByVal data As String) As String
        Try
            Dim utf8 As New UTF8Encoding
            Dim inBytes() As Byte = utf8.GetBytes(data) ' ascii encoding uses 7
            'bytes for characters whereas the encryption uses 8 bytes, thus we use utf8
            Dim ms As New MemoryStream() 'instead of writing the encrypted
            'string to a filestream, I will use a memorystream

            Dim aes As New RijndaelManaged()
            Dim cs As New CryptoStream(ms, aes.CreateEncryptor(_key, _iv), CryptoStreamMode.Write)

            cs.Write(inBytes, 0, inBytes.Length) ' Start encrypt
            cs.FlushFinalBlock() ' finish encrypt

            Return Convert.ToBase64String(ms.GetBuffer(), 0, ms.Length)
        Catch ex As Exception
            Throw ex
        End Try
    End Function
End Class